<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderlyName">
        <el-input
          v-model="queryParams.elderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同期限" prop="contractDateRange">
        <el-date-picker
          clearable
          v-model="queryParams.contractDateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间"
          value-format="YYYY-MM-DD"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="contractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="合同名称" align="center" prop="contractName" width="150"/>
      <el-table-column label="合同编号" align="center" prop="contractNo" width="150"/>
      <el-table-column label="老人姓名" align="center" width="150">
        <template #default="scope">
          {{ scope.row.elderlyName || "-" }}
        </template>
      </el-table-column>

      <el-table-column label="老人身份证号" align="center" width="200">
        <template #default="scope">
          {{ scope.row.idCard || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="合同期限" align="center" width="260">
        <template #default="scope">
          <span
            >{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }} ——
            {{ parseTime(scope.row.endDate, "{y}-{m}-{d}") }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="contractStatus">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.contractStatus)">
            {{ scope.row.contractStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="150">
        <template #default="scope">
          {{ scope.row.creatorName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Eye"
            @click="handleView(scope.row)"
            v-hasPermi="['system:contract:view']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="contractRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="合同编号">
          {{ form.contractNo }}
        </el-form-item>
        <el-form-item label="合同名称">
          {{ form.contractName }}
        </el-form-item>
        <el-form-item label="老人姓名">
          {{ form.oldManName }}
        </el-form-item>
        <el-form-item label="老人身份证号">
          {{ form.idCardNo }}
        </el-form-item>
        <el-form-item label="入住单号">
          {{ form.checkInNo }}
        </el-form-item>
        <el-form-item label="合同期限">
          {{ form.contractTerm }}
        </el-form-item>
        <el-form-item label="合同状态">
          <el-tag :type="getStatusTagType(form.contractStatus)">
            {{ form.contractStatus }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contract">
import { useRouter} from "vue-router";
import { ref, reactive, toRefs, onMounted ,getCurrentInstance,onActivated} from "vue";
import useTagsViewStore from '@/store/modules/tagsView';
const tagsViewStore = useTagsViewStore();

const router = useRouter();

import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
} from "@/api/system/contract";

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");

const contractList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: null,
    elderlyId: null,
    startDate: null,
    endDate: null,
    contractStatus: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 判断合同状态 */
function calculateContractStatus(contract) {
  const now = new Date();
  const startDate = new Date(contract.startDate);
  const endDate = new Date(contract.endDate);
  
  if (contract.contractStatus=='已失效') {
    return '已失效';
  }else if (now < startDate) {
    return '未生效';
  }else if (now >= startDate && now < endDate) {
    return '生效中';
  }else if (now >= endDate) {
    return '已过期';
  }
  return contract.contractStatus || '未知状态';
}

/** 获取状态标签类型 */
function getStatusTagType(status) {
  switch (status) {
    case '未生效':
      return 'info';
    case '生效中':
      return 'success';
    case '已过期':
      return 'warning';
    case '已失效':
      return 'danger';
    default:
      return 'info';
  }
}

function handleView(row) {
  // router.push({
  //   path: "/system/contract/ContractView",
  //   query: {
  //     contractId: row.id,
  //     contractName: row.contractName,
  //   },
  // });
  const contractData = JSON.stringify(row);
  router.push({
    path: "/system/contract/ContractView",
    query: {
      contractData: contractData, // 传递完整合同数据
      contractName: row.contractName,
    },
  });
}

/** 查询合同列表 */
function getList() {
  loading.value = true;
  listContract(queryParams.value).then((response) => {
    // 计算每个合同的动态状态
    contractList.value = response.rows.map(contract => ({
      ...contract,
      contractStatus: calculateContractStatus(contract)
    }));
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    contractName: null,
    contractNo: null,
    elderlyId: null,
    startDate: null,
    endDate: null,
    contractStatus: null,
    signTime: null,
    contractFile: null,
    creator: null,
    createTime: null,
    partyCName: null,
    partyCPhone: null,
    terminationSubmitter: null,
    terminationTime: null,
    terminationAgreement: null,
    checkInManagementId: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("contractRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加合同";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getContract(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改合同";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contractRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateContract(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addContract(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除合同编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delContract(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/contract/export",
    {
      ...queryParams.value,
    },
    `contract_${new Date().getTime()}.xlsx`
  );
}

onMounted(() => {
  getList();
});

onActivated(() => {
  getList();
});
</script>